import config from "@/config"
import http from "@/utils/request"
import qs from 'qs'

export default {
	token: {
		url: `${config.API_URL}/auth/login`,
		name: "登录获取TOKEN",
		post: async function(data={}){
            data = qs.stringify(data)
			return await http.post(this.url, data);
		}
	},
	logout: {
		url: `${config.API_URL}/auth/logout`,
		name: "登出",
		post: async function(){
			return await http.post(this.url);
		}
	},
	menuTree: {
		//遍历
		forAll: function(d,f){
			if (d) {
				for(let i=0;i<d.length;i++) {
					if (d[i]) {
						f(d[i])
						if (d[i].children) {
							this.forAll(d[i],f)
						}
					}
				}
			}
		},
		// 将 服务的 meunu 结构转换为 scui 需要的 menu 结构
		// scui menu 结构详见 menu.json 
		build: function(data) {
			var arr = []
			for(var i=0;i<data.length;i++) {
				arr.push( this.transfer(data[i]) )
			}
			return arr
		},
		removeFirstSlash: function(data) {
			if (!data) return data
			if (data == '') return data
			var first = data.substring(0,1)
			if (first == '/')
				data = data.substring(1)
			if (first == "\\")
				data = data.substring(1)
			return data
		},
		transfer: function(data) {
			if (!(data.func.funView))
				data.func.funView = ''
			if (!(data.func.funPath))
				data.func.funPath = '';
			//
			var menuOption = {
				id: String(data.func.id),
				parentId: String(data.func.pid),
				name: data.func.name,
				path: data.func.funPath,
				component: this.removeFirstSlash(data.func.funView == null ? data.func.funPath : data.func.funView),
				orderNum: data.func.orderNum,
				permissionId: data.func.permissionId,
				meta: {
					icon: data.func.icon,
					hidden: data.func.noVisible == 1,
					disabled: data.func.isDisabled == 1,
					title: data.func.name,
				},
				children: []
			}
			//0:菜单,1:功能,2:链接,3:内嵌页
			if (data.func.funType == 0) {
				//iframe / menu / link
				menuOption.meta.type = 'menu'
			}
			else if (data.func.funType == 1) {
				menuOption.meta.type = 'button'
			}
			else if (data.func.funType == 2) {
				menuOption.meta.type = 'link'
			}
			else if (data.func.funType == 3) {
				menuOption.meta.type = 'iframe'
			}
			//children
			if (data.children) {
				for (var j=0;j<data.children.length;j++) {
					 menuOption.children.push(this.transfer(data.children[j]))
				}
			}
			//
			if (menuOption.path == "/dashboard") {
				menuOption.meta.affix = true
			}			
			//
			return menuOption
		}
	}
}